<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/* JoomLeague League Management and Prediction Game for Joomla!
 * @version $Id: Match.class.php 1126 2008-06-09 05:45:04Z julienv $
 * @package Joomleague
 * @copyright Copyright (C) 2007  JoomLeague
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see _joomleague_license.txt
 *  
 * Homepage: http://www.joomleague.de
 * Support: htt://www.joomleague.de/forum/
 * 
 * This file is part of JoomLeague.
 *  
 * JoomLeague is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * Please note that the GPL states that any headers in files and
 * Copyright notices as well as credits in headers, source files
 * and output (screens, prints, etc.) can not be removed.
 * You can extend them with your own credits, though...
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * The "GNU General Public License" (GPL) is available at
 * http://www.gnu.org/copyleft/gpl.html.
*/ 

class Match extends JLClass{
  
  var $match_id;
  var $match_number;
// new for date by match Gucky 2007/05/25
  var $match_date;
// new for date by match Gucky 2007/05/25 ends
  var $project_id;
  var $round_id;
  var $matchpart1; //JL_Team->id
  var $matchpart2; //JL_Team->id
  var $matchpart1_result;
  var $matchpart2_result;
  var $matchpart1_bonus;
  var $matchpart2_bonus;
// new for period results Gucky 2007/05/25
	var $matchpart1_result_split;
  var $matchpart2_result_split;
  var $matchpart1_legs;
  var $matchpart2_legs;
// new for period results Gucky 2007/05/25 ends
  var $match_result_type; //0=normal,1=addtime,2=penalty
  var $matchpart1_result_ot;
  var $matchpart2_result_ot;
  var $match_result_detail;
  var $alt_decision;
  var $matchpart1_result_decision;
  var $matchpart2_result_decision;
  var $decision_info;
  var $count_result; //boolean
  var $playground_id;
  var $referee_id;
  var $crowd;
  var $checked_out;
  var $checked_out_time;
  var $summary;
  //remark for roster management: i kept homeroster / awayroster
  //till we are through with development
  var $homeroster;
  var $awayroster;
  var $show_report;
    
  var $published;
  var $modified; // last modification time
  var $modified_by; // user id
  
  function Match( &$db ) {
		$this->mosDBTable( '#__joomleague_matches', 'match_id', $db );
	}
	
// function save_array changed for date per match and period results
// Gucky 2007/05/25
  function save_array( $cid=null, $post=null, $zusatz=false, $project_id){
    global $my;
    
    $datatable[0] = '#__joomleague_matches';
  	$fields = $this->_db->getTableFields( $datatable );
  	foreach($fields as $field) {
  		$query = '';
  		$datafield = array_keys($field);
  		if ($zusatz) $fieldzusatz = $cid;
  		foreach($datafield as $keys) if (isset($post[$keys.$fieldzusatz])) {
   			$result=$post[$keys.$fieldzusatz];
            if ($keys=='match_date') $result.=' '.$post['match_time'.$fieldzusatz];
            if ($keys=='matchpart1_result_split' || $keys=='matchpart2_result_split' || $keys=='homeroster' || $keys=='awayroster') {
	    		$result=trim(join(";",$result));
		    } 
   			if ($keys=='alt_decision' && $post[$keys.$fieldzusatz]==0) $query.=", matchpart1_result_decision=NULL, matchpart2_result_decision=NULL, decision_info=''";
		    if ($keys=='matchpart1_result_decision' && strtoupper($post[$keys.$fieldzusatz])=='X' && $post['alt_decision'.$fieldzusatz]==1) $result='';
		    if ($keys=='matchpart2_result_decision' && strtoupper($post[$keys.$fieldzusatz])=='X' && $post['alt_decision'.$fieldzusatz]==1) $result='';
	        if (!is_numeric($result)) $vorzeichen = "'"; else $vorzeichen = "";
		    if (strstr("crowd, homeroster, awayroster, show_report, matchpart1_result, matchpart1_bonus, matchpart1_legs, matchpart2_result,
  			          matchpart2_bonus, matchpart2_legs, matchpart1_result_decision, matchpart2_result_decision, matchpart1_result_split,
  			          matchpart2_result_split, matchpart1_result_ot, matchpart2_result_ot,", $keys.',') && $result=='' && isset($post[$keys.$fieldzusatz])) {
			  $result = 'NULL';
			  $vorzeichen = '';	
		    }
		    //if ($keys=='crowd' && $post['crowd'.$fieldzusatz]=='') $result='0';
		    if ($result!='' || $keys=='summary' || $keys=='match_result_detail') {
			  if ($query) $query.=', ';
			  $query.=$keys.'='.$vorzeichen.$result.$vorzeichen;
		    }
  		}
  	}
  	$query = 'UPDATE #__joomleague_matches 
              SET '.$query.', `modified`=NOW(), `modified_by`='.$my->id.' 
              WHERE match_id='.$cid;
  	$this->_db->setQuery($query);
  	$this->_db->query($query);
  	
  	$joomleague = new JoomLeague($this->_db);
    $joomleague->load($project_id);
    if ($joomleague->usePrediction()) {
      $joomleague->savePredictionPoints($cid);
    }
    return true;
  }
  
  function publish_array( $cid=null, $post=null, $publish=1, $myid=0 ) {
		if (!is_array( $cid ) || count( $cid ) < 1) {
			$this->_error = "No items selected.";
			return false;
		}
		
		$cids = implode( ',', $cid );
		
		$this->_db->setQuery( "UPDATE $this->_tbl SET published='$publish'"
		. "\nWHERE match_id IN ($cids) AND (checked_out=0 OR (checked_out='$myid'))"
		);
    print $this->_db->getQuery();
		if (!$this->_db->query()) {
			$this->_error = $this->_db->getErrorMsg();
			return false;
		}
		
		if (count( $cid ) == 1) {
			$this->checkin( $cid[0] );
		}
		$this->_error = '';
		return $post["id"];
	}
  
  function setNull( $cid=null, $post, $myid=0 ) {
		if (!is_array( $cid ) || count( $cid ) < 1) {
			$this->_error = "No items selected.";
			return false;
		}
		
		$cids = implode( ',', $cid );
// added matchpart1_result_split and matchpart2_result_split to query Gucky 2007/05/25
// removed false ; after decision_info, set a , instead Gucky 2007/05/26
		$this->_db->setQuery( "UPDATE $this->_tbl SET 
                matchpart1_result = NULL, 
                matchpart2_result = NULL,
                matchpart1_result_split = NULL, 
                matchpart2_result_split = NULL,
                matchpart1_legs = NULL,
                matchpart2_legs = NULL, 
                match_result_type = 0,
                matchpart1_result_ot = NULL, 
                matchpart2_result_ot = NULL,
                matchpart1_result_decision = NULL, 
                matchpart2_result_decision = NULL,
                homeroster = NULL, 
                awayroster = NULL,
                alt_decision = 0,
                decision_info = '',
                crowd = 0,
                referee_id = 0,
							  summary = '',
							  show_report = 0,
							  match_result_detail = '',
                modified = '0000-00-00 00:00:00',
                modifed_by = 0 
         WHERE match_id IN ($cids) AND (checked_out=0 OR (checked_out='$myid'))"
		);
    print $this->_db->getQuery();
		if (!$this->_db->query()) {
			$this->_error = $this->_db->getErrorMsg();
			return false;
		}
		
		if (count( $cid ) == 1) {
			$this->checkin( $cid[0] );
		}
		$this->_error = '';
		return $post["id"];
	}
  
  function removeMatch( $cid=null ) {
    	if (!is_array( $cid ) || count( $cid ) < 1) {
		$this->_error = "No items selected.";
		return false;
	}
    foreach($cid as $cids) {
	  $query = sprintf("DELETE FROM #__joomleague_match_events WHERE match_id = %s",$cids);
      $this->_db->setQuery($query);
	  $this->_db->query();
      $query = sprintf("DELETE FROM #__joomleague_matches WHERE match_id = %s",$cids);
      $this->_db->setQuery($query);
      $this->_db->query();
    }
    return true;
  }
  
  /**
   * return teams playing as JL_team objects
   *
   * @return array of JL_Team objects
   */
  function getTeams(){
  
    $teams = array();
    
    $team1 = new JL_Team( $this->_db);
    $team1->load($this->matchpart1);
    
    $team2 = new JL_Team( $this->_db);
    $team2->load($this->matchpart2);
    
    $teams[] = $team1;
    $teams[] = $team2;
    
    return $teams;
    
  }
  
  // new for roster management 2007/11/01
  /**
   * returns starters player id for the specified team
   *
   * @param int $team_id
   * @param int $position_id
   * @return array of player ids
   */
  function getRoster ($team_id, $position_id=0) {
    $query = "SELECT player_id 
              FROM #__joomleague_match_players 
              WHERE match_id = '".$this->match_id."'
                AND team_id = '".$team_id."' 
                AND came_in = 0";
    if ($position_id > 0) $query .= " AND position_id = '".$position_id."'";
    $query .= " ORDER BY position_id, ordering ASC";
    $this->_db->setQuery($query);
    return $this->_db->loadResultArray();
  }
  
  function getSubstitutes() {
    $in_out = array();
    $query = "SELECT mp.*, 
                     pt.project_id, pt.id AS ptid, pt2.id AS out_ptid, 
                     p.firstname, p.lastname, 
                     pos.name AS in_position,
                     pos2.name AS out_position, 
                     p2.firstname AS out_firstname, 
                     p2.lastname AS out_lastname 
              FROM #__joomleague_match_players AS mp
              LEFT JOIN #__joomleague_playertool AS pt ON mp.player_id = pt.player_id
              LEFT JOIN #__joomleague_players AS p ON mp.player_id = p.id
              LEFT JOIN #__joomleague_positions AS pos ON mp.position_id = pos.id
              LEFT JOIN #__joomleague_playertool AS pt2 ON mp.in_for = pt2.player_id
              LEFT JOIN #__joomleague_match_players AS mp2 ON (mp.in_for = mp2.player_id)
              LEFT JOIN #__joomleague_positions AS pos2 ON mp2.position_id = pos2.id
              LEFT JOIN #__joomleague_players AS p2 ON mp.in_for = p2.id
              WHERE pt.project_id ='".$this->project_id."' 
               AND mp.match_id = '".$this->match_id."' 
               AND mp.team_id = '".$this->matchpart1."' 
               AND mp.came_in = 1 
              GROUP BY mp.player_id 
              ORDER by in_out_time";
    $this->_db->setQuery($query);
    $in_out[$this->matchpart1] = $this->_db->loadObjectList();
    
    $query = "SELECT mp.*, pt.project_id, pt.id AS ptid, pt2.id AS out_ptid, p.firstname, p.lastname, pos.name AS in_position,
              pos2.name AS out_position, p2.firstname AS out_firstname, p2.lastname AS out_lastname FROM #__joomleague_match_players AS mp
              LEFT JOIN #__joomleague_playertool AS pt ON mp.player_id = pt.player_id
              LEFT JOIN #__joomleague_players AS p ON mp.player_id = p.id
              LEFT JOIN #__joomleague_positions AS pos ON mp.position_id = pos.id
              LEFT JOIN #__joomleague_playertool AS pt2 ON mp.in_for = pt2.player_id
              LEFT JOIN #__joomleague_match_players AS mp2 ON (mp.in_for = mp2.player_id)
              LEFT JOIN #__joomleague_positions AS pos2 ON mp2.position_id = pos2.id
              LEFT JOIN #__joomleague_players AS p2 ON mp.in_for = p2.id
              WHERE pt.project_id ='".$this->project_id."' AND mp.match_id = '".$this->match_id."' AND 
              mp.team_id = '".$this->matchpart2."' AND
              mp.came_in = 1 GROUP BY mp.player_id ORDER by in_out_time";
    $this->_db->setQuery($query);
    $in_out[$this->matchpart2] = $this->_db->loadObjectList();
    return $in_out;
  }
  // new for roster management 2007/11/01 ENDS
  
  // new editing part results 2007/11/02
  function editPart_results ($i, &$project, $backend=false) {
   if (!is_null($i)) {?>
    <a href="javascript:void(0)" onclick="switchMenu('part<?php
				echo $this->match_id;?>')"><img src="<?php echo JL_URL_FOLDER;?>/images/joomleague/sort01.gif" border="0" alt="<?php
				echo _JL_ADMIN_EDIT_MATRIX_ROUNDS_PART_RESULT;?>" /></a>
			<span id="part<?php echo $this->match_id;?>" style="display:none"><br />
    <?php
  }
			$partresults1=explode(";", $this->matchpart1_result_split);
        $partresults2=explode(";", $this->matchpart2_result_split);
        for ($x=0;$x<($project->game_parts);$x++) {
          echo ($x+1).".: ";
        	?>
          <input type="text" style="font-size:9px;" name="matchpart1_result_split<?php
          echo (!is_null($i)) ? $this->match_id : '';?>[]" value="<?php
          echo (isset($partresults1[$x])) ? $partresults1[$x] : '';?>" size="3" tabindex="1" class="inputbox"<?php
          if (!is_null($i)) { ?> onchange="<?php
            if ($backend) { ?>document.adminForm.cb<?php echo $i;?>.checked = true; isChecked(this.checked);<?php }
          else { ?>document.getElementById('cb<?php
          echo $i;?>').checked=true;<?php
          }?>"<?php
        } ?> />
          :
          <input type="text" style="font-size:9px;" name="matchpart2_result_split<?php
          echo (!is_null($i)) ? $this->match_id : '';?>[]" value="<?php
          echo (isset($partresults2[$x])) ? $partresults2[$x] : '';?>" size="3" tabindex="1" class="inputbox"<?php
          if (!is_null($i)) { ?> onchange="<?php
            if ($backend) { ?>document.adminForm.cb<?php echo $i;?>.checked = true; isChecked(this.checked);<?php }
          else { ?>document.getElementById('cb<?php
          echo $i;?>').checked=true;<?php
          }?>"<?php
        } ?> /><br />
      <?php }
      if ($project->allow_add_time == 1) {
        echo 'OT:'; ?>
        <input type="text" style="font-size:9px;" name="matchpart1_result_ot<?php
          echo (!is_null($i)) ? $this->match_id : '';?>" value="<?php
          echo (isset($this->matchpart1_result_ot)) ? $this->matchpart1_result_ot : '';?>" size="3" tabindex="1" class="inputbox"<?php
          if (!is_null($i)) { ?> onchange="<?php
            if ($backend) { ?>document.adminForm.cb<?php echo $i;?>.checked = true; isChecked(this.checked);<?php }
          else { ?>document.getElementById('cb<?php
          echo $i;?>').checked=true;<?php
          }?>"<?php
        } ?> />
        :
        <input type="text" style="font-size:9px;" name="matchpart2_result_ot<?php
          echo (!is_null($i)) ? $this->match_id : '';?>" value="<?php
          echo (isset($this->matchpart2_result_ot)) ? $this->matchpart2_result_ot : '';?>" size="3" tabindex="1" class="inputbox"<?php
          if (!is_null($i)) { ?> onchange="<?php
            if ($backend) { ?>document.adminForm.cb<?php echo $i;?>.checked = true; isChecked(this.checked);<?php }
          else { ?>document.getElementById('cb<?php
          echo $i;?>').checked=true;<?php
          }?>"<?php
        } ?> /><br />
        <?php
      }
      if (!is_null($i)) echo '</span>';
  }
}
?>
